<?php
namespace Xxfaxy\DryBundle\Controller;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;

class CacheController extends Controller
{

    public function indexAction(Request $request)
    {
        $crud = $this->get('service.crud');
        $cache = $crud->getCache();
        $list1 = $cache->keys('fixed*');
        $list2 = $cache->keys('else*');
        $list3 = array_merge($list1, $list2);
        unset($list1, $list2);
        $list = array();
        foreach($list3 as $key){
            if($cache->has($key, true)){
                $raw = $cache->get($key, true);
                if(time() >= $raw['time']){
                    $cache->remove($key, true);
                }
                else{
                    $list[] = array(
                        'key' => $key,
                        'time' => $raw['time'],
                        'time_string' => date('Y-m-d H:i:s', $raw['time']),
                        'data' => $raw['data'],
                        'rest' => $raw['time'] - time()
                    );
                }
            }
        }
        $data = array(
            'list' => $list
        );
        return $this->render('XxfaxyDryBundle:cache:index.html.twig', $data);
    }

    public function deleteAction(Request $request, $id)
    {
        $function = $this->get('service.common.function');
        $crud = $this->get('service.crud');
        $cache = $crud->getCache();
        if($cache->has($id, true)){
            $cache->remove($id, true);
        }
        $this->addFlash('message_success', $function->translation('operationSuccess'));
        return $this->redirectToRoute('cache_index');
    }

    public function deleteMd5Action(Request $request)
    {
        $function = $this->get('service.common.function');
        $crud = $this->get('service.crud');
        $cache = $crud->getCache();
        $list = $cache->keys('else*');
        foreach($list as $id){
            if($cache->has($id, true)){
                $cache->remove($id, true);
            }
        }
        $this->addFlash('message_success', $function->translation('operationSuccess'));
        return $this->redirectToRoute('cache_index');
    }

}
